const router = require('koa-router')()
//设置模块根路径
const mongo = require("../compents/mongo")
const ObjectId = require('mongodb').ObjectId;
const {postLogData} =require("../utils/misc")
// 设置根路径
router.prefix('/denglu')
const jwt = require('jsonwebtoken');

router.get('/test', async ctx => {
    // console.log(ctx);
    ctx.body = 'test'
})
// router.get('/login', async ctx => {
//     const { loginName, loginKey } = ctx.query
//     const res = await mongo.findOne("denglu", {loginName, loginKey})
//     if (res) {
//         token = jwt.sign({ _id: res._id }, 'cs-220107-token');
//         ctx.body = {data:res, token, msg: "接口请求成功", code: 20000 }
//     } else {
//         ctx.body = { msg: "接口请求失败", code: 30007 }
//     }
// })
router.post('/login', async ctx => {
    postLogData("登陆")
    const { loginName, loginKey } = ctx.request.body
    const res = await mongo.findOne("denglu", {loginName, loginKey})
    if (res) {
        token = jwt.sign({ _id: res._id }, 'cs-220107-token');
        ctx.body = {data:res, token, msg: "接口请求成功", code: 20000 }
    } else {
        ctx.body = { msg: "接口请求失败", code: 30007 }
    }
})


router.get('/info', async ctx => {
    const { token } = ctx.query
    const _id = await getIdByToken(token)
    const res = await mongo.findOne("denglu", { _id: ObjectId(_id) })
    const json = { name: res.name, roles: res.roles.split(','), avatar: res.avatar, introduction: res.introduction }
    ctx.body = { data: json, code: 20000, msg: "数据请求成功" }
})

const getIdByToken = (token) => {

    return new Promise((reslove, reject) => {
        jwt.verify(token, 'cs-220107-token', (error, decoded) => {
            if (error) throw error
            reslove(decoded._id)
        })
    })

}


module.exports = router //导出路由对象